<template>
  <div class="category-page">
    <Header />
    <!-- <Breadcrumb :items="breadcrumbItems" /> -->
    
    <div class="container">
      <component 
        :is="currentComponent" 
        :category="category" 
        :articles="articles" 
        :loading="loading" 
      />
    </div>
    
    <Footer />
  </div>
</template>

<script>
import Header from '@/components/Header'
import Footer from '@/components/Footer'
import Breadcrumb from '@/components/Breadcrumb'
import List from './List'
import Single from './Single'
import Gallery from './Gallery'
import Video from './Video'
import Link from './Link' // 假设有一个Link组件用于处理类型3的内容
import { getCategoryById, getArticlesByCategory } from '@/api/category'

export default {
  name: 'CategoryPage',
  components: {
    Header,
    Footer,
    Breadcrumb
  },
  props: {
    id: {
      type: [String, Number],
      required: true
    }
  },
  data() {
    return {
      category: {},
      articles: [],
      loading: false,
      breadcrumbItems: []
    }
  },
  computed: {
    currentComponent() {
      const type = this.category.categoryType
      console.log("类型"+type)
      if (!type) return null
      
      const components = {
        '1': List,     // 列表
        '2': Single,   // 单页
        '3': Link,     // 链接
        '4': Gallery,  // 图集
        '5': Video     // 视频
      }
      
      return components[type] || null
    }
  },
  watch: {
    id: {
      immediate: true,
      handler(newVal) {
        if (newVal) {
          this.fetchCategoryData()
        }
      }
    }
  },
  methods: {
    async fetchCategoryData() {
      this.loading = true
      try {
        const res = await getCategoryById(this.id)
        this.category = res.data
        this.generateBreadcrumb()
        
        // 如果是列表、图集或视频类型，获取文章数据
        if (['1', '4', '5'].includes(this.category.categoryType)) {
          const articleRes = await getArticlesByCategory(this.id, {
            page: 1,
            size: 10
          })
          console.log(articleRes)
          this.articles = articleRes.data
        }
      } catch (error) {
        console.error('获取栏目数据失败:', error)
        this.$router.replace('/404')
      } finally {
        this.loading = false
      }
    },
    generateBreadcrumb() {
      const items = [{ text: '首页', to: '/' }]
      
      if (this.category.parentId !== 0) {
        // 这里可以添加父栏目，需要根据实际情况调整
        items.push({
          text: '父栏目',
          to: `/category/${this.category.parentId}`
        })
      }
      
      items.push({
        text: this.category.categoryName,
        active: true
      })
      
      this.breadcrumbItems = items
    }
  }
}
</script>